package org.scratchcrew.web.cometd.handlers;

import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component("boardChannelSupport")
public class BoardChannelSupportImpl implements BoardChannelSupport {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	private static final String CHANNEL_PREFIX = "/scratchcrew/board/";
	private static final int CHANNEL_PREFIX_LENGTH = CHANNEL_PREFIX.length();
	private static final Pattern CHANNEL_PATTERN = Pattern.compile(Pattern
			.quote(CHANNEL_PREFIX)
			+ "\\d{1,18}");

	@Override
	public long getBoardIdByChannel(String channel)
			throws IllegalArgumentException {
		if (!isBoardChannel(channel)) {
			final String message = String.format("Invalid channel %s", channel);
			logger.error(message);
			throw new IllegalArgumentException(message);
		}

		final String strBoardId = channel.substring(CHANNEL_PREFIX_LENGTH);
		return Long.valueOf(strBoardId);
	}

	@Override
	public String getChannelByBoardId(Long boardId) {
		return CHANNEL_PREFIX + boardId.toString();
	}

	@Override
	public boolean isBoardChannel(String channel) {
		if (channel == null || !CHANNEL_PATTERN.matcher(channel).matches()) {
			return false;
		}

		return true;
	}

}
